﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Interactivity;

namespace WpfWordsLearner
{
	public class MouseMoveAction : TriggerAction<DataGrid>
	{
		protected override void OnAttached()
		{
			base.OnAttached();
		}

		protected override void OnDetaching()
		{
			base.OnDetaching();
		}

		protected override void Invoke(object parameter)
		{
			if (parameter != null && parameter is MouseEventArgs)
			{
				MouseEventArgs e = parameter as MouseEventArgs;
				var vm = (AssociatedObject.DataContext as ViewModels.Windows1ViewModel);

				if (e.LeftButton == MouseButtonState.Pressed && !vm.IsDragging)
				{
					Point position = e.GetPosition(null);
					Point _startPoint = vm.StartPoint;

					if (Math.Abs(position.X - _startPoint.X) > SystemParameters.MinimumHorizontalDragDistance ||
						Math.Abs(position.Y - _startPoint.Y) > SystemParameters.MinimumVerticalDragDistance)
					{
						StartDrag(e);
					}
				}
			}
		}

		private void StartDrag(MouseEventArgs e)
		{
			var vm = AssociatedObject.DataContext as ViewModels.Windows1ViewModel;
			DataGridRow row = (e.OriginalSource as DependencyObject).FindAnchestor<DataGridRow>();
			if (row == null || row.Item == null || !(row.Item is Model.WordsModel))
			{
				vm.IsDragging = false;
				return;
			}

			vm.IsDragging = true;
			bool ctrl = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl);

			DataObject daObj = new DataObject(typeof(Model.WordsModel), (row.Item as Model.WordsModel));
			DragDropEffects effect = ctrl ? DragDropEffects.Move : DragDropEffects.Copy;
			DragDropEffects de = DragDrop.DoDragDrop(AssociatedObject, daObj, effect);
			vm.IsDragging = false;
		}

		private System.Windows.Controls.DataGridRow GetDataFromListBox(DataGrid source, Point point)
		{
			UIElement element = source.InputHitTest(point) as UIElement;
			if (element != null)
			{
				object data = DependencyProperty.UnsetValue;
				while (element != null || !(element is System.Windows.Controls.DataGridRow) || data == DependencyProperty.UnsetValue)
				{
					data = source.ItemContainerGenerator.ItemFromContainer(element);

					if (data == DependencyProperty.UnsetValue)
					{
						element = System.Windows.Media.VisualTreeHelper.GetParent(element) as UIElement;
						if (element is System.Windows.Controls.Button)
							return null;
					}

					else if (element is System.Windows.Controls.DataGridRow)
					{
						return (element as System.Windows.Controls.DataGridRow);
					}
				}
			}
			return null;
		}
	}
}